﻿using Summer.Network;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Proto;
using Summer;
using GameServer.Model;
using GameServer.Mgr;
using Serilog;
using GameServer.Network;

namespace GameServer.Service
{
    /// <summary>
    /// 地图服务
    /// </summary>
    public class SpaceService : Singleton<SpaceService>
    {
        //地图字典
        private Dictionary<int,Space> spaceDict = new Dictionary<int, Space>();

        public void Start()
        {
            //位置同步请求
            SpaceManager.Instance.Init();
            MessageRouter.Instance.Subscribe<SpaceEntitySyncRequest>(_SpaceEntitySyncRequest);
            MessageRouter.Instance.Subscribe<SpaceEntityRoleInfoSyncRequest>(_SpaceEntityRoleInfoSyncRequest);
            MessageRouter.Instance.Subscribe<SyncSkillRequest>(_SyncSkillRequest);
        }

        private void _SyncSkillRequest(Connection conn, SyncSkillRequest msg)
        {
            var sp = conn.Get<Session>().Space;
            if (sp == null) return;
            sp.UpdateSkillInSpace(msg);
        }

        private void _SpaceEntityRoleInfoSyncRequest(Connection conn, SpaceEntityRoleInfoSyncRequest msg)
        {
            var sp = conn.Get<Session>().Space;
            if (sp == null) return;
            if (sp.thisSpaceBroker == null) sp.thisSpaceBroker = conn;
            sp.UpdateEntityRoleInfo(msg.CharacterRoleInfo);
        }

        public Space GetSpace(int spaceId)
        {
            return SpaceManager.Instance.GetSpace(spaceId);
        }


        private void _SpaceEntitySyncRequest(Connection conn, SpaceEntitySyncRequest msg)
        {
            //获取当前角色
            var sp = conn.Get<Session>().Space;
            if (sp == null) return;
            NEntity netEntity = msg.EntitySync.Entity;
            Entity serEntity = EntityManager.Instance.GeteEntity(netEntity.Id);
            float dist = Vector3Int.Distance(new Vector3Int(netEntity.Position.X, netEntity.Position.Y, netEntity.Position.Z), serEntity.Position);
            netEntity.Speed = serEntity.EntitySpeed;

            float dt = Math.Min(serEntity.PositionTime, 1.0f);
            float limit = serEntity.EntitySpeed*1000 * dt * 1.5f;
            //Log.Information("距离{0}，阈值{1}，间隔{2}", dist, limit, dt);
            //if (float.IsNaN(dist) || dist > limit)
            //{
            //    SpaceEntitySyncResponse resp = new SpaceEntitySyncResponse();
            //    resp.EntitySync = new NEntitySync();
            //    resp.EntitySync.Entity = serEntity.GetData();
            //    resp.EntitySync.Force = true;
            //    conn.Send(resp);
            //    return;
            //}
            sp.UpdateEntity(msg.EntitySync);
        }
    }
}
